package com.jixing.rengran.huaji.mvp.presenter;

import com.jixing.rengran.huaji.mvp.view.BaseView;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by l5544 on 2017/11/6.
 */

public abstract class BasePresenter<V extends BaseView> {
    private Reference<V> mViewRef;//使用弱引用，防止内存泄漏
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    protected V getView() {
        return mViewRef != null ? mViewRef.get() : null;
    }

    public void attachView(V view) {
        mViewRef = new WeakReference<>(view);
    }

    public boolean isAttached() {
        return mViewRef != null && mViewRef.get() != null;
    }

    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
        compositeDisposable.clear();
    }

    void addDisposable(Flowable flowable, Consumer consumer) {
        compositeDisposable.add(flowable.
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        getView().onError(throwable);
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        getView().hideProgress();
                    }
                })
                .subscribe(consumer));
    }
}
